package com.ty.tymusic.service.impl;

import com.ty.tymusic.dto.FileDto;
import com.ty.tymusic.dto.FileUploadDto;
import com.ty.tymusic.dto.request.FileUploadRequest;
import com.ty.tymusic.entity.File;
import com.ty.tymusic.enums.ExceptionType;
import com.ty.tymusic.enums.FileStatus;
import com.ty.tymusic.exception.BizException;
import com.ty.tymusic.mapper.FileMapper;
import com.ty.tymusic.repository.FileRepository;
import com.ty.tymusic.service.FileService;
import com.ty.tymusic.service.StorageService;
import com.ty.tymusic.utils.FileTypeTransformer;
import com.ty.tymusic.utils.StorageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

@Service
public class FileServiceImpl implements FileService {

    private Map<String, StorageService> storageServices;

    private FileRepository fileRepository;

    private FileMapper fileMapper;

    /**
     * @param fileUploadRequest:文件的
     * @return
     * @throws IOException
     */
    @Override
    @Transactional
    public FileUploadDto initUpload(FileUploadRequest fileUploadRequest) throws IOException {
        //创建File实体
        File file = fileMapper.createEntity(fileUploadRequest);
        file.setType(FileTypeTransformer.getFileTypeFromExt(fileUploadRequest.getExt()));
        file.setStorage(StorageUtil.getDefaultStorage());
        File saveFile = fileRepository.save(file);

        //通过接口获得STS令牌
        FileUploadDto fileUploadDto = storageServices.get(StorageUtil.getDefaultStorage().name()).initFileUpload();

        fileUploadDto.setKey(saveFile.getKey());
        fileUploadDto.setFileId(saveFile.getId());

        return fileUploadDto;
    }

    @Override
    public FileDto finishUpload(String id) {
        Optional<File> fileOptional = fileRepository.findById(id);
        if (!fileOptional.isPresent()) {
            throw new BizException(ExceptionType.FILE_NOT_FOUND);
        }
        //Todo:只有上传者才能更新finish

        File file = fileOptional.get();
        file.setStatus(FileStatus.UPLOADED);

        return fileMapper.toDto(fileRepository.save(file));
    }

    @Autowired
    public void setFileMapper(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
    }

    @Autowired
    public void setFileRepository(FileRepository fileRepository) {
        this.fileRepository = fileRepository;
    }

    @Autowired
    public void setStorageServices(Map<String, StorageService> storageServices) {
        this.storageServices = storageServices;
    }
}
